package com.cyt.chattlibrary.message;


import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.cyt.chattlibrary.message.util.FileUtils;
import com.homegoods.aroutercomment.UserService;

import java.io.File;

/**
 * @author QiQi
 * @ClassName: VoiceMessageHandler
 * @date 2018/10/22
 * @description
 */
public class VoiceMessageHandler extends MessageHandler<VoiceMessage> {
    private static final String TAG = VoiceMessageHandler.class.getName();
    private static final String VOICE_PATH = "/voice/";
    @Autowired
    public UserService userService;

    public VoiceMessageHandler(Context context) {
        super(context);
    }

    @Override
    public void decodeMessage(Message msg, VoiceMessage content) {
        Uri uri = obtainVoiceUri(getContext());
        String name = msg.getMessageId() + ".amr";
        if (msg.getMessageId() == 0) {
            name = msg.getSendTime() + ".amr";
        }
        File file = new File(uri.toString() + name);
        if (!TextUtils.isEmpty(content.getBase64()) && !file.exists()) {
            byte[] data = Base64.decode(content.getBase64(), 2);
            file = FileUtils.byte2File(data, uri.toString() + VOICE_PATH, name);
            content.setUri(Uri.fromFile(file));
            content.setBase64(null);
        }
    }

    @Override
    public void encodeMessage(Message msg) {
        VoiceMessage model = (VoiceMessage) msg.getContent();
        Uri uri = obtainVoiceUri(getContext());
        byte[] voiceData = FileUtils.getByteFromUri(model.getUri());
        File file;
        String base64 = Base64.encodeToString(voiceData, 2);
        model.setBase64(base64);
        String name = msg.getMessageId() + ".amr";
        file = FileUtils.byte2File(voiceData, uri.toString() + VOICE_PATH, name);
        if (file != null && file.exists()) {
            model.setUri(Uri.fromFile(file));
        }

    }

    private Uri obtainVoiceUri(Context context) {
        File file = context.getFilesDir();
        String path = file.getAbsolutePath();
        String userId = userService.getUserId();
        return Uri.parse(path + File.separator + userId);
    }
}
